| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { z } from 'zod';
- import { AppDataSource } from '@/server/data-source';
- import { UserService } from '@/server/modules/users/user.service';
- import { UserSchema } from '@/server/modules/users/user.entity';
- import { ErrorSchema } from '@/server/utils/errorHandler';
- import { authMiddleware } from '@/server/middleware/auth';
- import { AuthContext } from '@/server/types/context';
- import { logger } from '@/server/utils/logger';
- // 初始化用户服务
- const userService = new UserService(AppDataSource);
- // 路径参数Schema
- const GetUserParams = z.object({
- id: z.coerce.number().int().positive().openapi({
- param: { name: 'id', in: 'path' },
- description: '用户ID',
- example: 1
- })
- });
- // 响应Schema
- const GetUserResponse = z.object({
- code: z.number().openapi({ example: 200 }),
- message: z.string().openapi({ example: 'success' }),
- data: UserSchema
- });
- // 路由定义
- const routeDef = createRoute({
- method: 'get',
- path: '/{id}',
- middleware: [authMiddleware],
- request: {
- params: GetUserParams
- },
- responses: {
- 200: {
- description: '成功获取用户详情',
- content: {
- 'application/json': { schema: GetUserResponse }
- }
- },
- 400: {
- description: '请求参数错误',
- content: {
- 'application/json': { schema: ErrorSchema }
- }
- },
- 401: {
- description: '未授权',
- content: {
- 'application/json': { schema: ErrorSchema }
- }
- },
- 403: {
- description: '权限不足',
- content: {
- 'application/json': { schema: ErrorSchema }
- }
- },
- 404: {
- description: '用户不存在',
- content: {
- 'application/json': { schema: ErrorSchema }
- }
- },
- 500: {
- description: '服务器内部错误',
- content: {
- 'application/json': { schema: ErrorSchema }
- }
- }
- },
- tags: ['用户管理']
- });
- // 创建路由实例
- const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
- try {
- // 获取当前用户
- const currentUser = c.get('user');
- if (!currentUser) {
- logger.error('未获取到用户信息');
- return c.json({ code: 401, message: '未授权' }, 401);
- }
- // 获取路径参数
- const { id } = c.req.valid('param');
-
- // 检查权限:管理员可以查看所有用户,普通用户只能查看自己
- const isAdmin = await userService.isAdmin(currentUser.id);
- if (!isAdmin && currentUser.id !== id) {
- logger.error('用户 %d 权限不足,无法查看用户 %d 的详情', currentUser.id, id);
- return c.json({ code: 403, message: '权限不足' }, 403);
- }
- // 查询用户详情
- logger.api('用户 %d 查询用户 %d 详情', currentUser.id, id);
- const user = await userService.findOne(id);
-
- const response: z.infer<typeof GetUserResponse> = {
- code: 200,
- message: 'success',
- data: user
- };
- return c.json(response, 200);
- } catch (error) {
- logger.error('获取用户详情失败: %o', error);
- const message = error instanceof Error ? error.message : '获取用户详情失败';
- const statusCode = message.includes('不存在') ? 404 : 500;
-
- const errorResponse = {
- code: statusCode,
- message
- };
- return c.json(errorResponse, statusCode);
- }
- });
- export default app;
|